package com.ithuameng.notice.controller;

import com.ithuameng.notice.config.ApplicationContextProvider;
import com.ithuameng.notice.netty.MyWebSocketHandler;
import io.netty.channel.Channel;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/netty")
public class NettyController {

    private SimpleMessageListenerContainer sysNoticeContainer = (SimpleMessageListenerContainer) ApplicationContextProvider
            .getApplicationContext().getBean("sysNoticeContainer");

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 页面刷新关闭时调用此方法
     * 关闭websocket连接 | 取消mq监听
     */
    @GetMapping("/close")
    public void closeConnection() {
        Channel channel = MyWebSocketHandler.userChannelMap.get("admin");
        if (channel != null) {
            channel.close();
        }
        sysNoticeContainer.removeQueueNames("system_notice_queue");
    }

    /**
     * 交换机队列绑定
     */
    @GetMapping("/binding")
    public void createRabbitmqConfig() {
        // 创建rabbitmq管理器(以前都是使用配置类 @Configuration)
        RabbitAdmin rabbitAdmin = new RabbitAdmin(rabbitTemplate.getConnectionFactory());
        // 声明exchange
        DirectExchange exchange = new DirectExchange("system_notice_exchange");
        // 创建queue
        Queue queue = new Queue("system_notice_queue", true);
        // 声明exchange和queue的绑定关系
        Binding binding = BindingBuilder.bind(queue).to(exchange).withQueueName();
        // 声明队列与绑定队列
        rabbitAdmin.declareQueue(queue);
        rabbitAdmin.declareBinding(binding);
    }
}
